﻿using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Text;

namespace DotNetExtensions.Core
{
    public class JsonIncrementor : Singleton<JsonIncrementor>
    {
        private readonly string filename;
        private FileStream fileStream;
        private JObject keyValues;
        private JsonIncrementor()
        {
            filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "id.json");
            fileStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            fileStream.Position = 0;
            keyValues = new JObject();
            if (fileStream.Length > 0 && fileStream.CanRead)
            {
                byte[] buffer = new byte[fileStream.Length];
                fileStream.Read(buffer, 0, buffer.Length);
                string data = Encoding.UTF8.GetString(buffer);
                keyValues = JObject.Parse(data);
            }
        }
        private void Flush()
        {
            byte[] buffer = Encoding.UTF8.GetBytes(keyValues.ToString());
            fileStream.Position = 0;
            fileStream.Write(buffer, 0, buffer.Length);
            fileStream.Flush();
        }
        public long Create(string key)
        {
            lock (this)
            {
                long result;
                if (keyValues.ContainsKey(key))
                {
                    long value = keyValues.GetValue(key).ToObject<long>();
                    result = value + 1;
                    keyValues[key] = result;
                }
                else
                {
                    result = 1;
                    keyValues.Add(key, 1);
                }
                Flush();
                return result;
            }
        }
    }
}
